package vip.meeet.network.nginx;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

public class NginxConnect {

    private static final int NUM = 20;

    private static final CountDownLatch countDownLatch = new CountDownLatch(NUM);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(NUM);
        LinkedList<Future> futures = new LinkedList<>();
        for(int i=0;i<NUM;i++){
            Future<?> future = executorService.submit(new ConnectTask());
            futures.add(future);
        }
        while (!isAllDone(futures)){
            TimeUnit.SECONDS.sleep(5);
        }
        executorService.shutdownNow();
    }

    private static boolean isAllDone(List<Future> futureList){
        for(Future future : futureList){
            if(!future.isDone()){
                return false;
            }
        }
        return true;
    }

    private static class ConnectTask implements Runnable{

        @Override
        public void run() {
            countDownLatch.countDown();
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int i=0;i<1000;i++){
                try {
                    CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("Mozilla/5.0").build();
                    HttpGet httpGet = new HttpGet("http://localhost:8088");
                    httpClient.execute(httpGet);
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
